#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PageObjects.ACToys.ACToysBasePage import ACToysBasePage
from Utils.Element import Element
from Utils.PropertiesParsor import ParsePageProperty
from Config.GlobalVariables import OPERATION_ATTEMPT

parse_string = ParsePageProperty().parse_string
parse_locator = ParsePageProperty().parse_locator
set_property_value = ParsePageProperty().set_property_value


class TransformerTradePage(ACToysBasePage):

    @staticmethod
    def parse_url():
        return parse_string('ACToys.TransformerTradePage.url')

    @staticmethod
    def parse_title():
        return parse_string('ACToys.TransformerTradePage.title')

    @staticmethod
    def username_value():
        return parse_string('ACToys.TransformerTradePage.username_value')

    @staticmethod
    def password_value():
        return parse_string('ACToys.TransformerTradePage.password_value')

    def username_textbox(self):
        return Element(self.driver, parse_locator('ACToys.TransformerTradePage.username_textbox'))

    def password_textbox(self):
        return Element(self.driver, parse_locator('ACToys.TransformerTradePage.password_textbox'))

    def submit_button(self):
        return Element(self.driver, parse_locator('ACToys.TransformerTradePage.submit_button'))

    def username_link_logged_in(self, username):
        locate_type = parse_locator('ACToys.TransformerTradePage.username_link_logged_in')[0]
        locate_expression = parse_locator('ACToys.TransformerTradePage.username_link_logged_in')[1].format(username)
        return Element(self.driver, (locate_type, locate_expression))

    def search_textbox(self):
        return Element(self.driver, parse_locator('ACToys.TransformerTradePage.search_textbox'))

    def search_button(self):
        return Element(self.driver, parse_locator('ACToys.TransformerTradePage.search_button'))

    def login_opt(self, username, password):
        self.logger.info("Login ACToys")
        try:
            self.logger.debug("Wait TransformerTradePage Title Display")
            self.wait.title_is(self.parse_title())
            self.logger.debug("Clear UsernameTextbox")
            self.username_textbox().clear()
            self.logger.debug("Send Username '{0}' To UsernameTextbox".format(username))
            self.username_textbox().send_keys(username)
            self.logger.debug("Clear PasswordTextbox")
            self.password_textbox().clear()
            self.logger.debug("Send Password '{0}' To UsernameTextbox".format(password))
            self.password_textbox().send_keys(password)
            self.logger.debug("Click Submit Button")
            self.submit_button().click()
            if self.redirect_link().is_displayed():
                self.logger.debug("Click Redirect Link if it is displayed")
                self.redirect_link().click()
        except Exception as e:
            self.logger.error("Login Failed: {0}".format(e))
            raise e

    def set_cookies_opt(self, username):
        self.logger.info("Set ACToys Cookies")
        try:
            if self.username_link_logged_in(username).is_displayed():
                self.logger.debug("Get Page Cookies Successfully")
                cookies = self.driver.get_cookies()
                self.logger.debug("Set Page Cookies Into PageProperty Cookies")
                set_property_value("ACToys.TransformerTradePage.cookies", cookies)
            else:
                self.logger.debug("Set Empty List Into PageProperty Cookies")
                set_property_value("ACToys.TransformerTradePage.cookies", [])
        except Exception as e:
            self.logger.error("Failed To Set Cookies Property: {0}".format(e))
            raise e

    def go_(self):
        self.logger.info("Let's Go ACToys")
        self.browser.new_window(parse_string("ACToys.TransformerTradePage.url"))
        self.browser.switch_to_last_window()
        cookies = parse_string("ACToys.TransformerTradePage.cookies")
        if cookies:
            self.logger.debug("Add cookies to page and refresh")
            for cookie in cookies:
                self.add_cookie(cookie)
            self.browser.refresh()
            return True
        else:
            for login_attempt in range(OPERATION_ATTEMPT):
                if self.username_link_logged_in(self.username_value()).is_displayed():
                    return True
                else:
                    self.logger.info("Login NO.{0} Attempts".format(login_attempt + 1))
                    self.login_opt(self.username_value(), self.password_value())
            return False

    def go(self):
        if not self.go_():
            self.logger.error("Cannot Login In {0} Attempts, Quit".format(OPERATION_ATTEMPT))
            self.browser.close()
            self.browser.switch_to_first_window()
            return False
        else:
            self.set_cookies_opt(self.username_value())
            if parse_string("ACToys.TransformerTradePage.cookies"):
                self.logger.error("Fail To Set Page Cookies, Quit")
                self.browser.close()
                self.browser.switch_to_first_window()
                return False
            else:
                self.logger.debug("Login And Set Page Cookies Successfully")
                self.browser.close()
                self.browser.switch_to_first_window()
                return True

if __name__ == '__main__':
    a = TransformerTradePage("")
    print(a.search_content())
